import { _decorator, director, Node, Scene } from 'cc';



import { NetDefine } from '../Cmd/NetDefine';
import { PlayerInfo } from '../Cmd/PlayerInfo';

import { Config } from '../Common/Config';
import { PlayerHeadImage } from '../Cmd/PlayerHeadImage';
import { Login } from '../Cmd/Login';
import LoadMgr from '../Load/LoadMgr';

import { GameResult } from '../Cmd/GameResult';
import PlazaMgr from '../Plaza/PlazaMgr';
import { GameConfig } from '../Cmd/GameConfig';
import { RankingResult } from '../Cmd/RankingResult';
import { DiceGame } from '../Plaza/Game2/DiceGame';

const { ccclass, property } = _decorator;

@ccclass('WsMgr')
export class WsMgr {


    private client: WebSocket;
    private  mGame: DiceGame ;
    private loadMgr: LoadMgr = null;
    private plazaMgr: PlazaMgr = null;
   
    private mPlayerInfo: PlayerInfo = null;//服务器返回的玩家个人信息
    private mPlayerHeadImage: PlayerHeadImage = null;//服务器返回的玩家个人信息(头像)
    private static instance: WsMgr;//通讯单例
    private mLogin: Login;//保存的登录信息
    private mI18n;//保存的登录语言
    private tableType: number;//幸运轮盘房间类别1，大奖多，2，中奖多

    private redBlacConfig:GameConfig;//游戏配置

    private gameList:GameResult[]=[];//游戏开奖历史记录
    private gameListIndex:number=0;//游戏开奖历史记录

    public mRankingResult :RankingResult;

    private constructor() { }

    public static getInstance(): WsMgr {
        if (WsMgr.instance == null) {
            WsMgr.instance = new WsMgr();
            WsMgr.instance.open();
        }
        return WsMgr.instance;
    }


    private open(): void {
        this.connectWebSocket();
        var t2 = setInterval(() => {
            this.heart();
        }, 5000)
    }

    

    saveLoginInfo(login: Login) {
        if (this.mLogin == null) {
            this.mLogin = login;
        }

    }
    saveI18n(i18n) {
        if (this.mI18n == null) {
            this.mI18n = i18n;
        }

    }

    connectWebSocket() {


        let client = new WebSocket(Config.WSS_URL);


        // 保存WebSocket实例，以便在其他地方使用
        this.client = client;
        client.onopen = function (event) {
            console.log("WebSocket open");

        };

        client.onerror = function (error) {
            console.log("WebSocket error:", error);

        };

        client.onmessage = function (event) {

            //  console.log("服务器发送内容："+event.data); // 输出: 内容
            this.onMessageReceived(event.data);
        }.bind(this);

        client.onclose = function (event) {
            alert('please restart');
            console.log("WebSocket onclose");

        };


    }

    onMessageReceived(message) {
        // 当收到服务器消息时，更新UI
        // try {
        var obj = JSON.parse(message);
        // console.log('解析main:%s,sub:%s,cmd:%s ' , obj.main,obj.sub,obj.cmd);

        switch (obj.main) {
            case NetDefine.GAME_MAIN:
                this.updateUI(obj);
                break;
            case 0:
              //  console.log('心跳main:%s,sub:%s,cmd:%s ' , obj.main,obj.sub,obj.cmd);
                break
            default:
                break;
        }

        // } catch (error) {
        //     console.log("解析异常：" + error); // 输出: 内容
        // }

    }

    updateUI(data) {
        // 
        var cmd = data.cmd;
        let SUB = data.sub
        switch (SUB) {

           
            case NetDefine.GAME_SUB_SOCKET_ERROR:
                //错误信息
                console.log('GAME_SUB_SOCKET_ERROR=', cmd);
                alert(cmd.msg);
                break;
            case NetDefine.GAME_SUB_SOCKET_SUCCESS:
                //创建连接成功,进行登录
                this.login();
                break;
            case NetDefine.GAME_C_SUB_USER_HEAD_INFO_RETURN://玩家头像信息
                console.log('GAME_C_SUB_USER_HEAD_INFO_RETURN=', cmd);
                this.mPlayerHeadImage=cmd;
                
                break;


            case NetDefine.GAME_C_SUB_ENTER_ROOM_RETURN:
                //登录成功,返回个人信息  
                this.mPlayerInfo = cmd;
                console.log('GAME_C_SUB_ENTER_ROOM_RETURN=', this.mPlayerInfo);
           
                break;
 
            case NetDefine.GAME_C_SUB_BET_RETURN:
                let  result: GameResult; 
                result=cmd;
                if (result!=null) {
                result.id=++this.gameListIndex;
                const  length =this.gameList.length;
                const max=60;
                if (length>=max) {
                    this.gameList= this.gameList.slice(10);
                    this.gameList[max-10]=result;
                }else{  
                 this.gameList[length]=result;
                    }
       
                console.log('GAME_C_SUB_BET_RETURN=', this.gameList);
                }

                break;

            case NetDefine. GAME_SUB_GAME_CONFIG:
                //游戏配置
                this.redBlacConfig=cmd;
                console.log('GAME_SUB_GAME_CONFIG=', cmd);
                break; 
            case NetDefine. GAME_C_SUB_MATCH_RANKING_RETURN:
                console.log('GAME_C_SUB_MATCH_RANKING_RETURN=', cmd);
                 break
            case NetDefine. GAME_C_SUB_MATCH_RANKING_SELF_RETURN:
                console.log('GAME_C_SUB_MATCH_RANKING_SELF_RETURN=', cmd);
                this.mRankingResult=cmd; 
        
                break     
               
            default:
                break;
        }
        this.sendUIMessage(SUB, cmd);

    }
    private currentScene: Config = Config.SCENE.LOAD;

    initGameMgr(mTurntable: DiceGame) {
        this.currentScene = Config.SCENE.GAME;
        this.mGame = mTurntable;
    }

    initLoadMgr(loadMgr: LoadMgr) {
        this.currentScene = Config.SCENE.LOAD;
        this.loadMgr = loadMgr;
    }

    initPlazaMgr(plaza: PlazaMgr) {
        this.currentScene = Config.SCENE.PLAZA;
        this.plazaMgr = plaza;
    }
    

    login() {
        let cmd = {
            uid: this.getLoginInfo().uid,
            token: this.getLoginInfo().token,
            liveid: this.getLoginInfo().liveid,
            stream: this.getLoginInfo().stream,
            viewingTableId: this.getLoginInfo().viewingTableId,
            isLoadImageHead: this.mPlayerHeadImage == null ? 0 : 1,
        }
        this.webSend(NetDefine.GAME_MAIN, NetDefine.GAME_C_SUB_ENTER_ROOM, cmd);
    }

   

    heart() {
        this.webSend(0, 0, null);
    }

    bet(bet:number,tableType:number,isRed:number) {
        let cmd = {
            uid: this.getLoginInfo().uid,
            token: this.getLoginInfo().token,
            liveid: this.getLoginInfo().liveid,
            stream: this.getLoginInfo().stream,
            bet:bet,
            tableType:tableType,
            isRed:isRed
        }
        this.webSend(NetDefine.GAME_MAIN, NetDefine.GAME_C_SUB_BET, cmd);
    }
   

    /***通用指令 */
    webSend(main, sub, cmd) {
        //发送押注分数给服务器
        let message = {
            main: main,
            sub: sub,
            cmd: cmd

        };
        let msg = JSON.stringify(message);

        this.sendMessage(msg);
    }

    



    // 如果需要发送数据到WebSocket服务器
    sendMessage(message) {
        if (this.client && this.client.readyState == WebSocket.OPEN) {
            this.client.send(message);
            // console.log('sendMessage:'+message);
        } else {
            this.connectWebSocket();
        }
    }
    
    public getPlayerInfo() {
        return this.mPlayerInfo;
    }

    
    public getLoginInfo() {
        return this.mLogin;
    }
    
    public getPlayerHeadImage() {
        return this.mPlayerHeadImage;
    }

    

    public getI18n() {
        return this.mI18n;
    }

    
    public isLoadScene() {
        return this.loadMgr != null && this.currentScene == Config.SCENE.LOAD;
    }

   
    public isGameScene() {
        return this.mGame != null && this.currentScene == Config.SCENE.GAME;
    }
    
    public sendUIMessage(SUB: number, cmd) {

        if (this.isGameScene()) {
            this.mGame.UIMessage(SUB, cmd);

        }  
    }

    public joinTableType(tableType:number) {
        this.tableType=tableType;
    }
    public getTableType() {
      return  this.tableType;
    }
    public getGameConfig() {
        return  this.redBlacConfig;
      }

      public getGameList() {
        return  this.gameList;
      }

    public getMatchRanking() {
        this.webSend(NetDefine.GAME_MAIN, NetDefine.GAME_C_SUB_MATCH_RANKING, null);
    }

}


